package com.example.project.projectspringcloud.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author :xujunbao
 * @ClassName com.inxedu.os.edu.service.user.SmsServiceStub
 * @description
 * @Create Date : 2014年9月22日 下午5:30:39
 */
@Data
public class TencentCloudMessageUtil {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    private String sdkappid;

    /**
     * sdkappid对应的appkey，需要业务方高度保密
     */
    private String strAppkey;

    private String msgContent;

    private String destNumber;

    public TencentCloudMessageUtil() {
    }

    public TencentCloudMessageUtil(String sdkappid, String strAppkey) {
        this.sdkappid = sdkappid;
        this.strAppkey = strAppkey;
    }

    /**
     * 发送短信
     *
     * @param destNumber
     * @param msgContent
     */
    public void sendMsg(String destNumber, String msgContent) {
        try {

            String url = String.format("https://yun.tim.qq.com/v3/tlssmssvr/sendsms?sdkappid=%s&random=%s&content=%s",
                    sdkappid,
                    String.valueOf((int) (1 + Math.random() * (100 - 1 + 1))),
                    URLEncoder.encode(msgContent, "UTF-8"));
            logger.info(HttpUtil.post(url, sendmsgparam(destNumber, msgContent)));
        } catch (Exception e) {
            logger.error("TencentCloudMessageUtil.sendMsg:", e);
        }
    }

    /**
     * 发送指定模板短信
     *
     * @param destNumber
     * @param sign
     * @param tplId
     * @param params
     * @return
     */
    public String sendMsgPoint(String destNumber, String sign, String tplId, String... params) {
        String result = "";
        try {
            String url = String.format("https://yun.tim.qq.com/v3/tlssmssvr/sendsms?sdkappid=%s&random=%d",
                    sdkappid,
                    (int) (1 + Math.random() * (100 - 1 + 1)));
            result = HttpUtil.post(url, sendmsgparamPoint(destNumber, sign, Integer.parseInt(tplId), params));
            logger.info(result);
        } catch (Exception e) {
            logger.error("TencentCloudMessageUtil.sendMsgPoint:", e);
        }
        return result;
    }

    /**
     * 群发
     *
     * @param destNumber
     * @param msgContent
     */
    public void sendMsgBatch(String[] destNumber, String msgContent) {
        try {
            String url = String.format("https://yun.tim.qq.com/v3/tlssmssvr/sendmultisms2?sdkappid=%s&random=%d&content=%s",
                    sdkappid,
                    (int) (1 + Math.random() * (100 - 1 + 1)),
                    URLEncoder.encode(msgContent, "UTF-8"));
            String result = HttpUtil.post(url, sendmsgparamBatch(destNumber, msgContent));
            logger.info(result);
        } catch (Exception e) {
            logger.error("TencentCloudMessageUtil.sendMsgBatch:", e);
        }
    }

    /**
     * 发送短信数据整理
     *
     * @param destNumber
     * @param sign
     * @param tplId
     * @param params
     * @return
     */
    public String sendmsgparamPoint(String destNumber, String sign, int tplId, String... params) {
        if (StringUtils.isEmpty(destNumber)) {
            return "";
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> tel = new HashMap<String, Object>();
        tel.put("nationcode", "86");
        tel.put("phone", "" + destNumber);
        // 0:普通短信, 1:营销短信
        map.put("type", "0");
        // 短信签名
        map.put("sign", sign);
        // 模板ID
        map.put("tpl_id", tplId);
        String[] arr = params;
        map.put("params", params);

        String strPhone = destNumber;
        // 将strAppkey和 strPhone拼接后再求md5
        String sig = StringUtil.md5(strAppkey + strPhone);
        // app凭证
        map.put("sig", sig);
        map.put("extend", "");
        map.put("ext", "");
        map.put("tel", tel);
        return gson.toJson(map);
    }

    /**
     * 发送短信数据整理
     *
     * @param destNumber
     * @param msgContent
     * @return
     */
    public String sendmsgparam(String destNumber, String msgContent) {
        if (StringUtils.isEmpty(destNumber) || StringUtils.isEmpty(msgContent)) {
            return "";
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> tel = new HashMap<String, Object>();
        tel.put("nationcode", "86");
        tel.put("phone", "" + destNumber);
        // 0:普通短信, 1:营销短信
        map.put("type", "0");
        map.put("msg", msgContent);
        String strPhone = destNumber;
        // 将strAppkey和 strPhone拼接后再求md5
        String sig = StringUtil.md5(strAppkey + strPhone);
        // app凭证
        map.put("sig", sig);
        map.put("extend", "");
        map.put("ext", "");
        map.put("tel", tel);
        return gson.toJson(map);
    }

    /**
     * 批量发送短信数据整理
     *
     * @param destNumber
     * @param msgContent
     * @return
     */
    public String sendmsgparamBatch(String[] destNumber, String msgContent) {
        if (ObjectUtils.isEmpty(destNumber) || StringUtils.isEmpty(msgContent)) {
            return "";
        }
        String phoneStrs = "";
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map> telList = new ArrayList<Map>();
        for (String num : destNumber) {
            Map<String, Object> tel = new HashMap<String, Object>();
            tel.put("nationcode", "86");
            tel.put("phone", "" + num);
            telList.add(tel);
            phoneStrs += num + ",";
        }
        // 0:普通短信, 1:营销短信
        map.put("type", "0");
        map.put("msg", msgContent);
        phoneStrs = phoneStrs.substring(0, phoneStrs.length() - 1);
        // 将strAppkey和 strPhone拼接后再求md5
        String sig = StringUtil.md5(strAppkey + phoneStrs);
        // app凭证
        map.put("sig", sig);
        map.put("extend", "");
        map.put("ext", "");
        map.put("tel", telList);
        return gson.toJson(map);
    }

    public static void main(String[] args) {
        TencentCloudMessageUtil smsUtil = new TencentCloudMessageUtil();
        String[] nums = {"13161090129", "18201604788"};
        smsUtil.sendMsgBatch(nums, "8888为您的验证码");
    }
}
